// 利萨如图形
// Lissajous generates GIF animations of random Lissajous figures.
package main

import (
	"image"
	"image/color"
	"image/gif"
	"io"
	"math"
	"math/rand"
	"os"
	"time"
)

//颜色
var palette = []color.Color{color.White, color.Black} //生成的是一个slice切片

const (
	whiteIndex = 0 // first color in palette
	blackIndex = 1 // next color in palette
)

func main() {
	// The sequence of images is deterministic unless we seed
	// the pseudo-random number generator using the current time.
	// Thanks to Randall McPherson for pointing out the omission.
	rand.Seed(time.Now().UTC().UnixNano())
	lissajous(os.Stdout)
}

func lissajous(out io.Writer) {
	const (
		cycles  = 5     // number of complete x oscillator revolutions
		res     = 0.001 // angular resolution
		size    = 100   // image canvas covers [-size..+size]
		nframes = 64    // number of animation frames
		delay   = 8     // delay between frames in 10ms units
	)

	freq := rand.Float64() * 3.0        // relative frequency of y oscillator
	anim := gif.GIF{LoopCount: nframes} //gif.GIF是一个struct类型
	phase := 0.0                        // 相移量
	for i := 0; i < nframes; i++ {      //生成一个单独的动画帧
		rect := image.Rect(0, 0, 2*size+1, 2*size+1)   //尺寸是201*201
		img := image.NewPaletted(rect, palette)        //颜色是黑白
		for t := 0.0; t < cycles*2*math.Pi; t += res { //画点成线
			x := math.Sin(t)              //x轴是sin函数
			y := math.Sin(t*freq + phase) //y轴也是sin函数，与x轴有一定偏移
			img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5),
				blackIndex) //画点+染色
		}
		phase += 0.1                           //相移
		anim.Delay = append(anim.Delay, delay) //设置延时
		anim.Image = append(anim.Image, img)   //添加帧
	}
	gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
}
